//
//  ViewController.m
//  FMDB的使用
//
//  Created by caominglei on 2018/2/4.
//  Copyright © 2018年 caominglei. All rights reserved.
//

#import "ViewController.h"
#import <FMDatabase.h>

@interface ViewController ()

@end

@implementation ViewController




- (void)viewDidLoad {
    [super viewDidLoad];
    NSArray *titleArr = [NSArray arrayWithObjects:@"创建/打开数据库",@"添加数据",@"删除数据",@"查找数据库", nil];
    for (int i = 0 ; i < 4; i++) {
        UIButton *optionalBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        optionalBtn.frame = CGRectMake(100, 80*i+150, 150, 50);
        [optionalBtn setTitle:titleArr[i] forState:UIControlStateNormal];
        [optionalBtn addTarget:self action:@selector(pressBtn:) forControlEvents:UIControlEventTouchUpInside];
        optionalBtn.backgroundColor = [UIColor orangeColor];
        optionalBtn.tag = 100 + i;
        [self.view addSubview:optionalBtn];
    }
    
}


- (void)pressBtn:(UIButton *)btn {
    if(btn.tag == 100){
        NSString *filePath = [NSHomeDirectory() stringByAppendingString:@"/Documents/db01.db"];
        _db = [FMDatabase databaseWithPath:filePath];
        if(_db){
            NSLog(@"创建数据库成功");
        }
        BOOL isOpen = [_db open];
        if(isOpen){
            NSLog(@"数据库打开成功");

        }
        
        NSString *createTableStr = @"create table if not exists stu(id integer primary key, age integer, name carchar(20));";
        BOOL isCreate = [_db executeUpdate:createTableStr];
        if(isCreate == YES ){
            NSLog(@"数据库创建成功");
        }
        BOOL isClose = [_db close];
        if(isClose){
            NSLog(@"数据库关闭成功");
            
        }
    }else if (btn.tag == 101){
        if(_db){
            if([_db open]){
                NSString *insertStr = @"insert into stu values(1,19,'Jack');";
                BOOL isOK = [_db executeUpdate:insertStr];
                if(isOK == YES){
                    NSLog(@"插入数据成功");
                }
            }
        }
    }else if (btn.tag == 102){
        NSString *filePath = [NSHomeDirectory() stringByAppendingString:@"/Documents/db01.db"];
        _db = [FMDatabase databaseWithPath:filePath];
        NSString *deleteStr = @"delete from stu where id = 1;";
        BOOL isOpen = [_db open];
        [_db executeUpdate:deleteStr];
    }else{
        NSString *queryStr = @"select * from stu ;";
        BOOL isOpen = [_db open];
        if(isOpen == YES){
            FMResultSet *result = [_db executeQuery:queryStr];
            //遍历所有结果
            while ([result next]) {
                //获取id字段内容
//                NSInteger stuID = [result intForColumn:@"id"];
                //获取名字字段内容
                NSString *name = [result stringForColumn:@"name"];
                //获取年龄字段内容
//                NSInteger age = [result intForColumn:@"age"];
//                NSLog(@"stuID:%ld name:%@ age:%ld",stuID,name,age);
                NSLog(@"stuID: name:%@ age:",name);

            }
        }
    }
}


@end
